/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jhu.profiteer;

import java.io.IOException;
import java.util.UUID;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jhu.profiteer.data.Account;
import jhu.profiteer.data.AccountJpaController;
import jhu.profiteer.data.exceptions.NonexistentEntityException;

/**
 *
 * @author Jeremy, Shiva
 */
public class LoginServlet extends HttpServlet {
   
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
      String submit = request.getParameter("submit");
      String url = "/index";
      
      // check for submit
      if(null == submit)
      {
    	  response.sendRedirect(url);
    	  return;
      }

      HttpSession session = request.getSession();
      Vector<String> notices = (Vector<String>)session.getAttribute("notices");
      AccountJpaController jc = new AccountJpaController();

      // check username
      String name = request.getParameter("username");

      if((null == name) || name.isEmpty())
      {
        if(null == notices) notices = new Vector<String>();
        notices.add("You must supply an user name.");
      }
      else
      {
        // submit = login
        if(submit.equalsIgnoreCase("Login"))
        {
          String pass = request.getParameter("password");

          if((null == pass) || pass.isEmpty())
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("You must supply a password.");
          }

          if(!jc.testForAccountWithName(name)) // account not found
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("The provider user name is not recognized.");
          }
          else // account found
          {
            Account a = jc.findAccountByName(name);

            if (a.isDamaged()) // account damaged
            {
              if(null == notices) notices = new Vector<String>();
              notices.add("Your account is damaged.");
            }
            // verify password
            else if (!a.verifyPassword(pass)) // incorrect password
            {
              if(null == notices) notices = new Vector<String>();
              notices.add("The password you provided is not correct.");
            }
            else // correct password
            {
              session.setAttribute("account", a);
              if(a.isAdministrator()) url = "/admin/index";
              else url = "/characterInformation";
            }
          }
        }
        // submit = forgot password
        else if(submit.equalsIgnoreCase("forgot password"))
        {
          if (!jc.testForAccountWithName(name)) // account not found
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("The provider user name is not recognized.");
          }
          else // account found
          {
            Account a = jc.findAccountByName(name);
            boolean sendEmail = true;
            // create a temp password
            String tempPass = UUID.randomUUID().toString().substring(0, 10);
            a.setPassword(tempPass);

            try
            {
              jc.edit(a);
            }
            catch(NonexistentEntityException ex)
            {
              if(null == notices) notices = new Vector<String>();
              notices.add("No account with that ID exists.");
              sendEmail = false;
            }
            catch(Exception ex)
            {
              if(null == notices) notices = new Vector<String>();
              notices.add("Error editing account.");
              sendEmail = false;
            }

            // send email
            if (sendEmail)
            {
              try
              {
                EmailUtil.SendMail(a.getEmailAddress(), tempPass);
              }
              catch(Exception ex)
              {
                if(null == notices) notices = new Vector<String>();
                notices.add("Error sending email.");
              }
            }
          }
        }
      }

      if(null != notices) session.setAttribute("notices", notices);
      this.getServletContext().getRequestDispatcher(url)
              .forward(request, response);
      return;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
